package cn.ipanel.bigdata.boot.date

/**
 * Author: lzz
 * Date: 2022/3/24 8:44
 */
case class Quarter(st: Long, et: Long, len: Int) extends Date(st, et) {

  override def prev(n: Int = 1): Quarter = {
    var q: Quarter = this
    for (_ <- 1 to n)
      q = Quarter(q.st - Date.DAY_TIME)
    q
  }

  override def next(n: Int = 1): Quarter = {
    var q: Quarter = this
    for (_ <- 1 to n)
      q = Quarter(q.et + Date.DAY_TIME + 1)
    q
  }

  lazy final val minDayQuarter: Int = 0
  lazy final val maxDayQuarter: Int = len - 1
  lazy final val lenDayQuarter: Int = maxDayQuarter + 1

  def getMonth(n: Int): Month = {
    if (n < 0) null
    else if (n > 2) null
    else {
      val year = asYear
      val ms = Date.Q_MONTH(year.toQuarter)
      year.getMonth(ms(n))
    }
  }

  def getDay(n: Int): Day = {
    if (n < minDayQuarter) Day(st)
    else if (n > maxDayQuarter) Day(st + Date.DAY_TIME * maxDayQuarter)
    else Day(st + Date.DAY_TIME * n)
  }

  def toYearIndex: Int = toQuarter
  override def toString: String = s"Week(${STime.toYYYYMMddHHmmss} To ${ETime.toYYYYMMddHHmmss})"
}

object Quarter {

  def unapply(yyyyMMdd: String): Option[(Long, Long, Int)] = {
    unapply(Time(yyyyMMdd).time)
  }

  def unapply(time: Long): Option[(Long, Long, Int)] = {
    val year = Year(time)
    val ms: Seq[Int] = Date.Q_MONTH(year.toQuarter)
    val m1 = year.getMonth(ms.head)
    val m2 = year.getMonth(ms(1))
    val m3 = year.getMonth(ms.last)
    Some(m1.st, m3.et, m1.len + m2.len + m3.len)
  }

  def apply(yyyyMMdd: String): Quarter = apply(Time(yyyyMMdd))
  def apply(time: Time): Quarter = apply(time.time)
  def apply(time: Long): Quarter = time match {
    case Quarter(st, et, len) => Quarter(st, et, len)
    case _ => null
  }
}